package com.example.huainanlive.ui

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import com.blankj.utilcode.util.GsonUtils
import com.demon.androidbasic.base.BaseViewModel
import com.demon.logger.Logger
import com.example.huainanlive.bean.ChangeSettingBean
import com.example.huainanlive.bean.GetCommentItem
import com.example.huainanlive.factory.WsAppResponse
import com.google.gson.reflect.TypeToken
import com.mindpointeye.websockt.IWebSocketListener
import com.mindpointeye.websockt.IWebSocketManager
import com.mindpointeye.websockt.javawebsocket.JavaWebSocketManager
import java.nio.ByteBuffer

class WsViewModel : BaseViewModel(), IWebSocketListener {

    companion object {
        private const val TAG = "LiveSocketService"
    }

    private val _startLive = MutableLiveData<String>()
    val startLive: LiveData<String> = _startLive

    private val _stopLive = MutableLiveData<String>()
    val stopLive: LiveData<String> = _stopLive

    private val _playLive = MutableLiveData<String>()
    val playLive: LiveData<String> = _playLive

    private val _endLive = MutableLiveData<String>()
    val endLive: LiveData<String> = _endLive

    private val _changeSetting = MutableLiveData<WsAppResponse<ChangeSettingBean>>()
    val changeSetting: LiveData<WsAppResponse<ChangeSettingBean>> = _changeSetting

    private val _addMessage = MutableLiveData<WsAppResponse<GetCommentItem>>()
    val addMessage: LiveData<WsAppResponse<GetCommentItem>> = _addMessage

    private val _addComment = MutableLiveData<WsAppResponse<GetCommentItem>>()
    val addComment: LiveData<WsAppResponse<GetCommentItem>> = _addComment

    private val _cancelComment = MutableLiveData<WsAppResponse<Int>>()
    val cancelComment: LiveData<WsAppResponse<Int>> = _cancelComment

    private val _addZan = MutableLiveData<WsAppResponse<Int>>()
    val addZan: LiveData<WsAppResponse<Int>> = _addZan

    // 经协商取消这个类型 先注释掉
//    private val _addAudience = MutableLiveData<WsAppResponse<Int>>()
//    val addAudience: LiveData<WsAppResponse<Int>> = _addAudience

     private val _peopleOnline = MutableLiveData<WsAppResponse<Int>>()
    val peopleOnline: LiveData<WsAppResponse<Int>> = _peopleOnline

    private val mWebSocketManager: IWebSocketManager = JavaWebSocketManager.INSTANCE

//    private val mSocketUrl =
//        "ws://112.30.213.205:8082/api/app/ws/app"

    class WsViewModelModelFactory : ViewModelProvider.Factory {
        override fun <T : ViewModel> create(modelClass: Class<T>): T {
            return WsViewModel() as T
        }
    }

    fun initWebSocket() {
//        val socketBuilder: Uri.Builder = Uri.parse(mSocketUrl).buildUpon()
//        socketBuilder.appendQueryParameter("userId", EasyStorer.get(ExtraName.apiToken, ""))
//        socketBuilder.appendQueryParameter("liveId", EasyStorer.get(ExtraName.LIVE_ID, ""))
//        mWebSocketManager.createSocketClient(socketBuilder.toString(), this)
        mWebSocketManager.createSocketClient(
            "ws://112.30.213.205:8082/api/app/ws/app?userId=111&liveId=1",
            this
        )
        Logger.d(TAG, "service onCreate")

    }

    fun onDestroys() {
        super.onCleared()
        Logger.d(TAG, "onDestroy")
        if (mWebSocketManager.isClosed()) {
            return
        }
        mWebSocketManager.closeConnect()
    }


    override fun onConnectSuccess() {
        Logger.d(TAG, "onConnectSuccess")
    }

    override fun onConnectFailed() {
        Logger.d(TAG, "onConnectFailed")
    }

    override fun onClose() {
        Logger.d(TAG, "onClose")

        if (mWebSocketManager.isClosed()) {
            return
        }
        mWebSocketManager.closeConnect()
        mWebSocketManager.reconnect()
    }

    override fun onOpen() {
        Logger.d(TAG, "onOpen createNotification")
    }

    override fun onMessage(vararg text: String?) {

        text.forEach {
            it?.let {
                val type = object : TypeToken<WsAppResponse<Any>>() {}.type
                val result: WsAppResponse<Any>
                Logger.d(TAG, "字符串：${it.toString()}")

                try {
                    //socket登陆
                    result = GsonUtils.fromJson<WsAppResponse<Any>>(it, type)
                    result?.let { list ->
                        Logger.d(TAG, "字符串：${GsonUtils.toJson(list.command)}")

                        when (list.command) {
                            //开始直播
                            "start_live" -> {
                                _startLive.postValue(
                                    GsonUtils.toJson(list.command)
                                )
                            }
                            "stop_live" -> {
                                _stopLive.postValue(
                                    GsonUtils.toJson(list.command)
                                )
                            }
                            "play_live" -> {
                                _playLive.postValue(
                                    GsonUtils.toJson(list.command)
                                )
                            }
                            "end_live" -> {
                                _endLive.postValue(
                                    GsonUtils.toJson(list.command)
                                )
                            }
                            //改变直播间设置
                            "change_setting" -> {
                                val typeWsGiftBean =
                                    object : TypeToken<WsAppResponse<ChangeSettingBean>>() {}.type
                                val changeSetting: WsAppResponse<ChangeSettingBean> =
                                    GsonUtils.fromJson(it, typeWsGiftBean)
                                _changeSetting.postValue(changeSetting)
                            }
                            //添加观众留言
                            "add_message" -> {
                                val typeWsGiftBean =
                                    object : TypeToken<WsAppResponse<GetCommentItem>>() {}.type
                                val addMessage: WsAppResponse<GetCommentItem> =
                                    GsonUtils.fromJson(it, typeWsGiftBean)
                                _addMessage.postValue(addMessage)

                            }
                            //添加主持人发言
                            "add_comment" -> {
                                val typeWsGiftBean =
                                    object : TypeToken<WsAppResponse<GetCommentItem>>() {}.type
                                val addComment: WsAppResponse<GetCommentItem> =
                                    GsonUtils.fromJson(it, typeWsGiftBean)
                                _addComment.postValue(addComment)

                            }
                            //撤销主持人发言
                            "cancel_comment" -> {
                                val typeWsGiftBean =
                                    object : TypeToken<WsAppResponse<Int>>() {}.type
                                val cancelComment: WsAppResponse<Int> =
                                    GsonUtils.fromJson(it, typeWsGiftBean)
                                _cancelComment.postValue(cancelComment)

                            }
                            //赞数量
                            "add_zan" -> {
                                val typeWsGiftBean =
                                    object : TypeToken<WsAppResponse<Int>>() {}.type
                                val addZan: WsAppResponse<Int> =
                                    GsonUtils.fromJson(it, typeWsGiftBean)
                                _addZan.postValue(addZan)

                            }
                            //观众数量
//                            "add_audience" -> {
//                                val typeWsGiftBean =
//                                    object : TypeToken<WsAppResponse<Int>>() {}.type
//                                val addAudience: WsAppResponse<Int> =
//                                    GsonUtils.fromJson(it, typeWsGiftBean)
//                                _addAudience.postValue(addAudience)
//
//                            }
                            //在线观众
                            "people_online" -> {
                                val typeWsGiftBean =
                                    object : TypeToken<WsAppResponse<Int>>() {}.type
                                val peopleOnline: WsAppResponse<Int> =
                                    GsonUtils.fromJson(it, typeWsGiftBean)
                                _peopleOnline.postValue(peopleOnline)

                                Logger.d(TAG, "people_online：${peopleOnline.command}")

                            }
                        }
                    }
                } catch (e: Exception) {
                    Logger.e("${TAG}:接收数据异常", "字符串：${e.message.toString()}")
                }
            }
        }


    }

    override fun onMessage(type: Int, vararg text: String?) {
        createMessageHandler(type, *text).handleMessage()

    }

    private fun createMessageHandler(type: Int, vararg text: String?): IMessageHandler {
        Logger.d(TAG, "createMessageHandler type is $type")
        if (text.isEmpty()) {
            return DefaultMessageHandler("", "")
        }
        val source = text[0]
        val message = text[1]
        return DefaultMessageHandler(source!!, message!!)
    }

    override fun onMessage(buffer: ByteBuffer) {
    }

    override fun onHeartBeatCheck(bytes: ByteArray) {
        mWebSocketManager.sendMessage(bytes)
    }

    interface IMessageHandler {
        companion object {
            /**
             * <pre>
             * 警报
            </pre> *
             *
             * `ALARM = 2;`
             */
            const val ALARM_VALUE = 2

            /**
             * <pre>
             * 状态
            </pre> *
             *
             * `STATUS = 3;`
             */
            const val STATUS_VALUE = 3

            /**
             * <pre>
             * 任务状态response: "{
             * taskId: 5d5fasdf5as5d5adad
             * status: 1
             * }"
             * 0: '未开始',
             * 1: '进行中',
             * 2: '已完成',
             * 3: '失败',
             * 4: '已取消
            </pre> *
             *
             * `TASK_STATUS = 4;`
             */
            const val TASK_STATUS_VALUE = 4
        }

        fun handleMessage()
    }

    class DefaultMessageHandler(private val source: String, private val message: String) :
        IMessageHandler {
        override fun handleMessage() {
            Logger.d(TAG, "onMessage source is $source \n message is $message")
        }
    }

}